<template>
  <div class="login-container">
    <!-- 顶部工具栏 -->
    <div class="top-bar">
      <el-switch v-model="isDark" inline-prompt active-icon="Moon" inactive-icon="Sunny" @change="toggleTheme" />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <el-card class="login-card">
      <!-- 登录表单 -->

      <div v-if="loginWay == 0 || loginWay == 1" class="count">
        <div class="relative">
          <h2>{{ $t("login.welLogin") }}</h2>
          <el-tag class="ml-2 absolute-rt">
            {{ defaultSettings.version }}
          </el-tag>
        </div>
        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form" v-if="loginWay == 0">
          <!-- 用户名 -->
          <div style="color: #1f75ec" class="tit">
            {{ $t("login.username") }}
          </div>
          <el-form-item>
            <div class="input-wrapper">
              <el-input ref="username" v-model="loginData.username" name="username" size="large" class="h-[37px]" />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <div class="tit">{{ $t("login.password") }}</div>
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item>
              <div class="input-wrapper">
                <el-input v-model="loginData.password" type="password" name="password" @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit" size="large" class="h-[37px] pr-2" show-password />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 验证码
        <el-form-item prop="captchaCode">
          <div class="input-wrapper">
            <svg-icon icon-class="captcha" class="mx-2" />
            <el-input
              v-model="loginData.captchaCode"
              auto-complete="off"
              size="large"
              class="flex-1"
              :placeholder="$t('login.captchaCode')"
              @keyup.enter="handleLoginSubmit"
            />

            <el-image
              @click="getCaptcha"
              :src="captchaBase64"
              class="captcha-image"
            />
          </div>
        </el-form-item> -->

          <!-- 登录按钮 -->
          <div class="xieyi">
            <svg-icon :icon-class="isRead ? 'juxin2' : 'juxin1'" @click="isRead = !isRead" />
            我已阅读并同意
            <span class="span">《艾图兰XX协议》</span>
            及
            <span class="span">《个人隐私保护政策》</span>
          </div>
          <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLoginSubmit"
            style="background-color: #1f75ec">
            {{ $t("login.login") }}
          </el-button>
        </el-form>
        <div class="imgCode" v-show="loginWay == 1">
          <div style="background-color: #fff">
            <img class="img" src="@/assets/images/image 23.png" alt="" />
          </div>
        </div>
        <div class="or">
          <div class="line"></div>
          OR
          <div class="line"></div>
        </div>
        <div class="wxBtn" v-if="loginWay == 0" @click="loginWay = 1">
          <svg-icon icon-class="wechart" class="mr-1" />
          使用微信扫码登陆
        </div>
        <div class="wxBtn" v-if="loginWay == 1" @click="loginWay = 0">
          <svg-icon icon-class="SVGplone" class="mr-1" />
          使用手机号扫码登陆
        </div>
        <div class="mt-7 text-sm" style="font-size: 0.7rem">
          <span @click="loginWay = 2" style="border-bottom: 1px solid #fff">
            暂无账号，
          </span>
          <span @click="loginWay = 2" style="color: #1f75ec; border-bottom: 1px solid #1f75ec">
            立即注册
          </span>
          <span @click="loginWay = 3" class="ml-4" style="border-bottom: 1px solid #fff">
            忘记密码
          </span>
        </div>
      </div>
      <!-- 注册表单 -->

      <div v-if="loginWay == 2">
        <el-icon color="#fff" size="24" @click="loginWay = 0">
          <component is="ArrowLeftBold" />
        </el-icon>
        <div class="count">
          <el-form ref="loginFormRef" :model="regData" class="login-form mt-2">
            <!-- 用户名 -->
            <div style="color: #1f75ec" class="tit">手机号</div>
            <el-form-item>
              <div class="input-wrapper">
                <el-input ref="username" v-model="regData.plone" name="plone" size="large" class="h-[37px]" />
              </div>
            </el-form-item>

            <!-- 密码 -->
            <div class="tit">{{ $t("login.password") }}</div>
            <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
              <el-form-item>
                <div class="input-wrapper">
                  <el-input v-model="regData.password" type="password" name="password" @keyup="checkCapslock"
                    @keyup.enter="handleLoginSubmit" size="large" class="h-[37px] pr-2" show-password />
                </div>
              </el-form-item>
            </el-tooltip>
            <div class="tit">再次输入密码</div>
            <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
              <el-form-item>
                <div class="input-wrapper">
                  <el-input v-model="regData.againPassword" type="password" name="againPassword" @keyup="checkCapslock"
                    @keyup.enter="handleLoginSubmit" size="large" class="h-[37px] pr-2" show-password />
                </div>
              </el-form-item>
            </el-tooltip>
            <div class="tit">验证码</div>
            <div style="display: flex; align-items: center; margin-bottom: 10px">
              <el-form-item style="flex: 1; margin-bottom: 0">
                <div class="input-wrapper">
                  <el-input v-model="regData.code" type="text" name="code" size="large" class="h-[37px] pr-2" />
                </div>
              </el-form-item>
              <div class="getCode h-[37px] ml-5">获取验证码</div>
            </div>

            <!-- 登录按钮 -->
            <div class="xieyi">
              <svg-icon :icon-class="isRead ? 'juxin2' : 'juxin1'" @click="isRead = !isRead" />
              我已阅读并同意
              <span class="span">《艾图兰XX协议》</span>
              及
              <span class="span">《个人隐私保护政策》</span>
            </div>
            <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLoginSubmit"
              style="background-color: #1f75ec">
              注 册
            </el-button>
          </el-form>
        </div>
      </div>
      <!-- 修改表单 -->
      <div v-if="loginWay == 3">
        <el-icon color="#fff" size="24" @click="loginWay = 0">
          <component is="ArrowLeftBold" />
        </el-icon>
        <div class="count">
          <el-form ref="loginFormRef" :model="editData" class="login-form mt-2">
            <!-- 用户名 -->
            <div style="color: #1f75ec" class="tit">手机号</div>
            <el-form-item>
              <div class="input-wrapper">
                <el-input ref="username" v-model="editData.plone" name="plone" size="large" class="h-[37px]" />
              </div>
            </el-form-item>

            <!-- 密码 -->
            <div class="tit">{{ $t("login.password") }}</div>
            <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
              <el-form-item>
                <div class="input-wrapper">
                  <el-input v-model="editData.password" type="password" name="password" @keyup="checkCapslock"
                    @keyup.enter="handleLoginSubmit" size="large" class="h-[37px] pr-2" show-password />
                </div>
              </el-form-item>
            </el-tooltip>
            <div class="tit">再次输入密码</div>
            <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
              <el-form-item>
                <div class="input-wrapper">
                  <el-input v-model="editData.againPassword" type="password" name="againPassword" @keyup="checkCapslock"
                    @keyup.enter="handleLoginSubmit" size="large" class="h-[37px] pr-2" show-password />
                </div>
              </el-form-item>
            </el-tooltip>
            <div class="tit">验证码</div>
            <div style="display: flex; align-items: center; margin-bottom: 10px">
              <el-form-item style="flex: 1; margin-bottom: 0">
                <div class="input-wrapper">
                  <el-input v-model="editData.code" type="text" name="code" size="large" class="h-[37px] pr-2" />
                </div>
              </el-form-item>
              <div class="getCode h-[37px] ml-5">获取验证码</div>
            </div>

            <!-- 登录按钮 -->
            <div class="xieyi">
              <svg-icon :icon-class="isRead ? 'juxin2' : 'juxin1'" @click="isRead = !isRead" />
              我已阅读并同意
              <span class="span">《艾图兰XX协议》</span>
              及
              <span class="span">《个人隐私保护政策》</span>
            </div>
            <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLoginSubmit"
              style="background-color: #1f75ec">
              保 存
            </el-button>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- ICP备案 -->
    <div class="icp-info" v-show="icpVisible">
      <p>
        Copyright © 2021 - 2024 youlai.tech All Rights Reserved. 有来技术
        版权所有
      </p>
      <p>皖ICP备20006496号-3</p>
    </div>
  </div>
</template>

<script setup lang="ts">
// 外部库和依赖
import { LocationQuery, useRoute } from "vue-router";

// 内部依赖
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI, { LoginData } from "@/api/auth";

import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

// 类型定义
import type { FormInstance } from "element-plus";

// 导入 login.scss 文件
import "@/styles/login.scss";
const checked1 = ref(false);
//登录方式
const loginWay = ref(0);
// 使用导入的依赖和库
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const route = useRoute();
// 窗口高度
const { height } = useWindowSize();
// 国际化 Internationalization
const { t } = useI18n();

// 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
//是否勾选
const isRead = ref(false);
// 是否显示 ICP 备案信息
const icpVisible = ref(true);
// 按钮 loading 状态
const loading = ref(false);
// 是否大写锁定
const isCapslock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 登录表单ref
const loginFormRef = ref<FormInstance>();

const loginData = ref<LoginData>({
  username: "18370774335",
  password: "1234567890",
} as LoginData);
// 注册表单ref
const regData = ref({
  plone: "",
  password: "",
  againPassword: "",
  code: "",
});
//修改表单ref
const editData = ref({
  plone: "",
  password: "",
  againPassword: "",
  code: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

/** 获取验证码 */
function getCaptcha() {
  AuthAPI.getCaptcha().then((data) => {
    loginData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

/** 登录表单提交 */
function handleLoginSubmit() {
  loading.value = true;
  userStore
    .login(loginData.value)
    .then(() => {
      const { path, queryParams } = parseRedirect();
      router.push({ path: path, query: queryParams });
    })
    .catch(() => {
      // getCaptcha();
    })
    .finally(() => {
      loading.value = false;
    });
  // 校验验证码
  // loginFormRef.value?.validate((valid: boolean) => {
  // if (valid) {
  // }
  // });
}

/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

onMounted(() => {
  // getCaptcha();
});
</script>

<style lang="scss" scoped>
.getCode {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 10px;
  border-radius: 8px;
  background-color: #1f75ec;
  color: #fff;
  font-size: 12px;
}

.count {
  width: 83%;
  margin: 0 auto;
}

.imgCode {
  display: flex;
  justify-content: center;

  .img {
    // width: 10rem;
    // height: 10rem;
    width: 225px;
    height: 225px;
    display: block;
  }
}

.or {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #ffffff;
  align-items: center;

  .line {
    width: 45%;
    height: 1px;
    background-color: #ffffff;
  }
}

.wxBtn {
  margin-top: 13px;
  width: 100%;
  border: 1px solid #f2f6fb;
  border-radius: 8px;
  font-size: 13px;
  color: #ffffff;
  height: 37px;
  display: flex;
  justify-content: center;
  align-items: center;
}

::v-deep .login-form .el-form-item--large {
  margin-bottom: 10px;
}

::v-deep .login-form .el-form-item__error {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.xieyi {
  color: #ffffff;
  font-size: 12px;
  margin-bottom: 12px;

  .span {
    color: #1f75ec;
  }
}
</style>
